﻿#define _DebugDrawBorder_uomBHP_ExpandClientRectange

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using DienLib.SummitLib;
//using Excel = Microsoft.Office.Interop.Excel;
//using Word = Microsoft.Office.Interop.Word;
using System.Diagnostics;

namespace DienLib.SummitLib
{
    /// <summary>
    /// Enum return Type for SummitFormLib.PerformDoubleClick()
    /// </summary>
    public enum DoubleClickJobTicket { NA, DUPLICATE_MANY, DUPLICATE_ONE_USERCANCEL, DUPLICATE_ONE_USEROK, NOT_FOUND };

    /// <summary>
    /// Wrapper for Summit Main Form
    /// </summary>
    public class SummitFormLib
    {
        #region Remote VARIABLE
        public const string PROGRESS_BAR = "workQueueProgressBar";
        ToolStripProgressBar a_ProgressBar;

        public const string BUT_NEWJOB = "tsNewJob";
        ToolStripSplitButton a_tsNewJob;

        public const string BUT_EXPORT = "tsExport";
        ToolStripButton a_tsExport;

        public const string BUT_EXIT = "tsExit";
        ToolStripButton a_tsExit;

        public const string SPLIT_CONTAINER1 = "splitContainer1";
        SplitContainer a_splitContainer1;   //Panel2.Controls[0].Controls[0] = object -> ultraTree1 as UltraTreeView

        //const string ULTRA_TREEVIEW = "ultraTree1";
        UltraTreeView a_treeJobPackage;

        public const string CUSTOMERVIEW_TOPPARENT = "ultraExplorerBar1";
        UltraExplorerBar a_ultraExplorerBar1;

        #endregion

        private Form _form;
        public SummitFormLib(Form SummitMainForm)
        {
            if (SummitMainForm == null) throw new NullReferenceException();
            if (SummitMainForm.IsDisposed) throw new Exception("New Job Form already Disposed or Closed");
            this._form = SummitMainForm;

            #region Init Remote Variable
            a_ProgressBar = DienLib.Reflector.GetField<ToolStripProgressBar>(_form, PROGRESS_BAR);
            a_tsNewJob = DienLib.Reflector.GetField<ToolStripSplitButton>(_form, BUT_NEWJOB);
            a_tsExport = DienLib.Reflector.GetField<ToolStripButton>(_form, BUT_EXPORT);
            a_tsExit = DienLib.Reflector.GetField<ToolStripButton>(_form, BUT_EXIT);
            a_ultraExplorerBar1 = new UltraExplorerBar(DienLib.Reflector.GetField<Control>(_form, CUSTOMERVIEW_TOPPARENT));
            a_ultraExplorerBar1.PerformCustomerClick(Enums.Customer.PTTEP); // Implement if no have then PopUp Client Not Found

            a_splitContainer1 = DienLib.Reflector.GetField<SplitContainer>(_form, SPLIT_CONTAINER1);
            a_treeJobPackage = new UltraTreeView(a_splitContainer1.Panel2.Controls[0].Controls[0].Controls[0]);

            /*PopUp.CountDownWPF.ShowDialog(5, "SUMMIT take time to load WELL INFO.!\r\n\"PLEASE WAIT FOR SOME SECONDS !\"", "WAIT FOR LOADING WELL INFO ...", delegate(object sender)
            {   // DELEGATE METHOD
                if (a_treeJobPackage == null) return false;
                //if (a_treeJobPackage.Nodes.Count == 0) return false; // Note : When not load, Nodes is 0
                return true; // Stop Count down
                // END DELEGATE
            });*/

            #endregion
            //MessageBox.Show("HUUUUUUU");
        }

        public DoubleClickJobTicket PerformDoubleClick(string ticket)
        {
            // CHECK IF DUPLICATE WITH CURRENT FARPAC : BY TICKET NUMBER
            int dupTimes = this.FoundDuplicateTicket(ticket);
            if (dupTimes > 1)
            {   // POPUP MANUAL CLICK OR DELETE
                DienLib.PopUp.PopUpOK.ShowDialog("Man ! So many Duplicate Job Ticket ... I don't know where to CLICK ???? ... ^_^" +
                "\r\n\r\nCan you VERIFY & CLEAN UP THEM FIRST ? Merci ...", string.Format("I AM CONFUSE NOW ! Ticket : \"{0}\"", ticket));
                return DoubleClickJobTicket.DUPLICATE_MANY;
            }
            else if (dupTimes == 1)
            {   // One Package Duplicate => Reopen
                //MessageBox.Show("3");
                DienLib.PopUp.PopUpResult res = DienLib.PopUp.PopUpOKCancel.ShowDialog("Are you sure to open this Job Package ?",
                    string.Format("REOPEN EXISTING JOB PACKAGE - Ticket : \"{0}\"", ticket));
                if (res == DienLib.PopUp.PopUpResult.CANCEL) return DoubleClickJobTicket.DUPLICATE_ONE_USERCANCEL; // If he doesn't want Reopen, return (for delete duplicate)
                UltraTreeNode node = a_treeJobPackage.ActiveNode; node.Expanded = true; // Confirm Expand to Visible see node that will click
                a_treeJobPackage.PerformDoubleClick(node.Nodes[0]); // Click if Duplicate only 1 & User Press OK
                return DoubleClickJobTicket.DUPLICATE_ONE_USEROK;
            }
            else
            {   // Job Ticke not found : Return
                DienLib.PopUp.PopUpOK.ShowDialog("Man ! I stare at all but cannot found any Job related to this Ticket ... So where to CLICK ???? ... ^_^" +
                "\r\n\r\nYou can CREATE NEW JOB PACKAGE FIRST ? See you man ...", string.Format("I CANNOT SEE Ticket : \"{0}\"", ticket));
                return DoubleClickJobTicket.NOT_FOUND;
            }
            // TO HERE mean sucess CLICKED
            return DoubleClickJobTicket.NA;
        }

        public bool PerformDoubleClickActiveJob()
        {
            UltraTreeNode node = a_treeJobPackage.ActiveNode;
            return a_treeJobPackage.PerformDoubleClick(a_treeJobPackage.ActiveNode.Nodes[0]);
        }

        public int FoundDuplicateTicket(string saleNumber)
        {
            a_treeJobPackage.ExpandAll();
            a_treeJobPackage.CollapseAll();
            //MessageBox.Show("a");
            bool duplicate = false;
            List<UltraTreeNode> mem = new List<UltraTreeNode>();
            foreach (UltraTreeNode node in a_treeJobPackage.Nodes)
            {
                a_treeJobPackage.ActiveNode = node;
                //MessageBox.Show("b");
                node.Selected = false;
                //MessageBox.Show("c");
                UltraTreeNode subnode = node.Nodes[0];
                //MessageBox.Show("c1");
                string fulltext = subnode.Text;
                //MessageBox.Show(fulltext);
                int start = fulltext.IndexOf("SO # ") + 5;
                //MessageBox.Show(start.ToString());
                int len = fulltext.IndexOf(")") - start;
                //MessageBox.Show(len.ToString());
                string ticket = node.Nodes[0].Text.Substring(start, len);
                //MessageBox.Show(ticket);
                if (ticket.Trim().ToLower() == saleNumber.Trim().ToLower())
                {   // Found Duplicate
                    //MessageBox.Show("d");
                    a_treeJobPackage.PerformAction(UltraTreeView.UltraTreeAction.SelectActiveNode);
                    duplicate = true;
                    mem.Add(node);
                }
            }

            if (duplicate)
            {
                PopUp.PopUpOK.ShowDialog(string.Format("Man ! I found \"DUPLICATE TICKET\" : \"{0}\" in these Job Packages !" +
                    "\r\nI already Highlighted in Blue Color ... in Summit Job List View" +
                    "\r\n\r\nCan you \"CAREFULLY CHECK & DELETE IT\" before create a new job" +
                    "\r\nto avoid Duplicate Job Package for One Ticket Number", saleNumber),
                    string.Format("DUPLICATE TICKET NUMBER : \"{0}\"", saleNumber));
                // EXPAND DUPLICATED NODE
                foreach (UltraTreeNode node in mem)
                {
                    //MessageBox.Show("e");
                    node.Expanded = true;
                }
            }
            //MessageBox.Show("f");
            // Nothing found return false silently : true already popup above
            return mem.Count;
        }

        public void StartNewJob()
        {
            if (a_ProgressBar.Visible == true) { PopUp.PopUpOK.ShowDialog("\"Summit\" stil \"Busy\" ! Wait for a while & \"TRY AGAIN LATER\" !", "SUMMIT BUSY PROCESS JOB !"); return; }
            // NOT BUSY
            if (a_tsNewJob.GetCurrentParent().InvokeRequired) a_tsNewJob.GetCurrentParent().Invoke((MethodInvoker)delegate() { a_tsNewJob.PerformButtonClick(); });
            else a_tsNewJob.PerformButtonClick();
        }

        public void ExitSummit()
        {
            if (a_ProgressBar.Visible == true) { PopUp.PopUpOK.ShowDialog("\"Summit\" stil \"Busy\" ! Wait for a while & \"TRY AGAIN LATER\" !", "SUMMIT BUSY PROCESS JOB !"); return; }
            // NOT BUSY
            if (a_tsExit.GetCurrentParent().InvokeRequired) a_tsExit.GetCurrentParent().Invoke((MethodInvoker)delegate() { a_tsExit.PerformClick(); });
            else a_tsExit.PerformClick();
        }

        public void ExportPackage(Enums.Customer customer, string wellNo, string shipTo = "", string wellAPI = "")
        {
            if (a_ProgressBar.Visible == true) { PopUp.PopUpOK.ShowDialog("\"Summit\" stil \"Busy\" ! Wait for a while & \"TRY AGAIN LATER\" !", "SUMMIT BUSY PROCESS JOB !"); return; }
            // NOT BUSY
            if (a_tsExport.GetCurrentParent().InvokeRequired) a_tsExport.GetCurrentParent().Invoke((MethodInvoker)delegate() { a_tsExport.PerformClick(); });
            else a_tsExport.PerformClick();
        }

        #region DISPOSE METHOD
        // Dispose() calls Dispose(true)
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // NOTE: Leave out the finalizer altogether if this class doesn't 
        // own unmanaged resources itself, but leave the other methods
        // exactly as they are. 
        ~SummitFormLib()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        // The bulk of the clean-up code is implemented in Dispose(bool)
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {   // Get in HERE if called explicitly, otherwise not need to enter HERE, after Destructor Managed Var which is Pointer to Real Object will fall out of stack automatically (like var out of scope)
                // free managed resources, (detach event ?)
                if (this._form != null) this._form = null; // Khong keu this._form.Dispose vi Reference toi _form. Ngoai ra do pass reference nen this._form = null khong anh huong gi toi object goc
                if (this.a_ProgressBar != null) this.a_ProgressBar = null;
                if (this.a_tsNewJob != null) this.a_tsNewJob = null;
                if (this.a_tsExport != null) this.a_tsExport = null;
                if (this.a_tsExit != null) this.a_tsExit = null;
                if (this.a_splitContainer1 != null) this.a_splitContainer1 = null;
                if (this.a_treeJobPackage != null) this.a_treeJobPackage = null;
            }

            /* free native resources if there are any.
            if (nativeResource != IntPtr.Zero) 
            {
                Marshal.FreeHGlobal(nativeResource);
                nativeResource = IntPtr.Zero;
            }*/
        }
        #endregion

        #region TEST_METHOD
#if DEBUG
        /// <summary>
        /// Static Test Method for DienLib.SummitLib.Command.InjectSummitTest. You will have to supply TestClass which is this class & implement InjectSummitTest() for this class
        /// </summary>
        public static void InjectSummitTest()
        {
            SummitFormLib summitLib = new SummitFormLib(SummitLib.Command.GetSummitMainForm());
            summitLib.FoundDuplicateTicket("9351453");
            summitLib.PerformDoubleClick("123456");
        }
#endif
        #endregion
    }
}